package com.jin.core.hack;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;

//RequestMappingHandlerMapping是专门来处理带有requestMapping注解的url的,并通过那种继承接口的方式加入到ioc
public class AutoPrefixUrlMapping extends RequestMappingHandlerMapping {

    @Value("${api-package}")
    private String apiPackagePath;


    @Override
    protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
        //接收原来的Url
        RequestMappingInfo mappingInfo =  super.getMappingForMethod(method, handlerType);
        if (mappingInfo!=null){
            String prefix = this.getPrefix(handlerType);
            //修改mappingInfo
            RequestMappingInfo newMappingInfo = RequestMappingInfo.paths(prefix).build().combine(mappingInfo);
            return newMappingInfo;
        }
        return mappingInfo;
    }

    private String getPrefix(Class<?> handlerType){
        //接收全包的路径
        String packageName = handlerType.getPackage().getName();
        //把全包路径中的一部分（我们指定的包路径）替换成空，剩下的部分就是我们要返回的(剩余包的前缀)
        String dotPath = packageName.replaceAll(this.apiPackagePath,"");
        return dotPath.replace(".","/");

    }


}
